import datetime
import json

from django.core import serializers
from rest_framework.response import Response
from rest_framework.views import APIView
# 体检 预约
from hospital_model.models import TimeQuantumModel, ProjectModel, TimeModel, DataTimeModel
from reservation_model.models import StatisticsModel, ReservationOrderModel

# 预约接口
from user_model.models import UserModel
from utils.age import GetInformation
from utils.check import is_check, is_sex, verify_datetime, verify_week, is_verify, is_timing
from utils.order import getrand

# 免费体检接口
"""
免费体检项目
步骤：
首先判断用户和项目是否存在  
y:继续判断
    判断用户是否符合预约该项目的资格
    Y：继续判断
        判断用户是否预约过（根据用户id查询）
        Y：继续判断
            免费预约次数
                Y：继续判断
                    预约时间是否在符合范围内
                    Y：继续判断
                        该时间段是否约满
                            Y：响应已经约满了
                            N：插入数据 响应成功
                    N：响应不在时间段内 重新选择时间                
                N：响应超过免费预约次数
        N：继续判断
            预约时间是否在符合范围内
            Y:继续判断
                该时间段是否约满
                    Y：响应已经约满了
                    N：插入数据 响应成功
            N：响应不在时间段内 重新选择时间
    N：响应用户没有改项目资格
N: 响应不存在时结果
"""
"""
class BookingRegisterView(APIView):
    def post(self, request, *args, **kwargs):
        ID_card = request.POST['ID_card']  # 预约人身份证号
        project_id = request.POST['project_id']  # 预约项目id
        time = request.POST['time']  # 预约时间

        # 查询是否可以预约
        a = ReservationOrderModel.objects.filter(project_id=project_id)
        a_json = json.loads(serializers.serialize('json', a))
        number = a_json[0]['fields']['reservation_number']
        r_time = a_json[0]['fields']['r_time']
        is_user = UserModel.objects.filter(u_IDcard=ID_card)
        if is_user.count() == 0:
            data = {
                'msg': "请检查用户您的输入信息",
                'code': 4000,
            }
            return Response(data)
        else:
            if a.count() == 0:
                project = ProjectModel.objects.filter(p_id=project_id)
                project_json = json.loads(serializers.serialize('json', project))
                # print(project_json)
                start_time = project_json[0]['fields']['start_age']
                end_time = project_json[0]['fields']['end_age']
                p_sex = project_json[0]['fields']['c_sex']
                # 免费次数
                free_number = project_json[0]['fields']['free_number']
                # 预交费用
                # p_prepay = project_json[0]['fields']['p_prepay']
                # 提前预约天数
                p_day = project_json[0]['fields']['p_day']

                sex = GetInformation(ID_card).get_sex()
                age = GetInformation(ID_card).get_age()

                if is_check(start_time, end_time, age) and is_sex(p_sex, sex):
                    if r_time == time:
                        if int(number) == 0:
                            order_number = getrand()
                            ReservationOrderModel.objects.create(r_order_number=order_number, reservation_number=1,
                                                                 r_IDcard=ID_card, project_id=project_id, r_time=time)
                            data = {
                                'msg': "预约成功",
                                'code': 2000,
                            }
                            return Response(data)
                        elif int(number) < 5:
                            order_number = getrand()
                            ReservationOrderModel.objects.create(r_order_number=order_number,
                                                                 reservation_number=(int(number) + 1),
                                                                 r_IDcard=ID_card, project_id=project_id, r_time=time)
                            data = {
                                'msg': "预约成功",
                                'code': 2000,
                            }
                            return Response(data)
                        else:
                            data = {
                                'msg': "预约满了",
                                'code': 4000,
                            }
                            return Response(data)
                    else:
                        # 判断是否在预约天数之内
                        data = {
                            'msg': "预约成功",
                            'code': 2001,
                        }
                        return Response(data)


                else:
                    data = {
                        'msg': "请查阅该项目使用人群",
                        'code': 4001,
                    }
                    return Response(data)
            else:
                is_t = ReservationOrderModel.objects.filter(project_id=project_id, r_time=time)
                if len(is_t) == 0:
                    pass
                else:
                    if int(number) == 0:
                        order_number = getrand()
                        ReservationOrderModel.objects.create(r_order_number=order_number, reservation_number=1,
                                                             r_IDcard=ID_card, project_id=project_id, r_time=time)
                        data = {
                            'msg': "预约成功",
                            'code': 2000,
                        }
                        return Response(data)
                    elif int(number) < 5:
                        order_number = getrand()
                        ReservationOrderModel.objects.create(r_order_number=order_number,
                                                             reservation_number=(int(number) + 1),
                                                             r_IDcard=ID_card, project_id=project_id, r_time=time)
                        data = {
                            'msg': "预约成功",
                            'code': 2000,
                        }
                        return Response(data)
                    else:
                        data = {
                            'msg': "预约满了",
                            'code': 4000,
                        }
                        return Response(data)
"""


# 老年体检
class BookingRegisterView(APIView):
    def post(self, request, *args, **kwargs):
        ID_card = request.POST['ID_card']  # 预约人身份证号
        project_id = request.POST['project_id']  # 预约项目id
        time = request.POST['time']  # 预约时间
        # timing = request.POST['timing']  # 预约时间点
        timing = request.POST['timing'][0:5]  # 预约时间点
        # print(timing, ID_card, project_id, time)
        # 查询是否可以预约
        a = ProjectModel.objects.filter(p_id=project_id)
        a_json = json.loads(serializers.serialize('json', a))
        # 获取该项目的开始预约时间 结束预约时间以及性别
        start_time = a_json[0]['fields']['start_age']
        end_time = a_json[0]['fields']['end_age']
        p_sex = a_json[0]['fields']['c_sex']
        is_user = UserModel.objects.filter(u_IDcard=ID_card)
        # 通过身份证号获取性别
        sex = GetInformation(ID_card).get_sex()
        # 通过身份证号获取年龄
        age = GetInformation(ID_card).get_age()
        # 判断用户是否存在
        if len(is_user) != 0:
            # 判断项目是否存在
            if len(a) == 0:
                data = {
                    'msg': "预约项目不存在",
                    'code': 4001,
                }
                return Response(data)
            else:
                # 判断预约表中是否有该项目
                is_null = ReservationOrderModel.objects.filter(r_IDcard=ID_card, project_id=project_id)
                if len(is_null) == 0:
                    # 判断年龄性别是否在范围内
                    # print(is_check(start_time, end_time, age), is_sex(p_sex, sex))
                    if is_check(start_time, end_time, age) and is_sex(p_sex, sex):
                        # 获取预约时间  判断预约时间是否在范围内
                        agreement_json = TimeQuantumModel.objects.filter(project__p_id=project_id).all()
                        agreement_lists = (json.loads(serializers.serialize('json', agreement_json)))
                        p_json = ProjectModel.objects.filter(p_id=project_id)
                        p = (json.loads(serializers.serialize('json', p_json)))[0]
                        time_quantum_list = []
                        for agreement_list in agreement_lists:
                            start = agreement_list['fields']['start_time']
                            end = agreement_list['fields']['end_time']
                            ProjectModel.objects.filter()
                            time_quantum_dict = {}
                            point_in_time = []
                            time_quantum_dict['p_money'] = p['fields']['p_money']
                            time_quantum_dict['p_prepay'] = p['fields']['p_prepay']
                            time_quantum_dict['p_day'] = p['fields']['p_day']
                            time_quantum_dict['p_number'] = p['fields']['p_number']
                            time_quantum_dict['start_time'] = agreement_list['fields']['start_time']
                            time_quantum_dict['end_time'] = agreement_list['fields']['end_time']
                            data_jsons = DataTimeModel.objects.filter(time__t_id=agreement_list['pk']).all()
                            serialization_list = (json.loads(serializers.serialize('json', data_jsons)))
                            week_list = []
                            li = []
                            for i in serialization_list:
                                week_list.append(i['fields']['d_data'])
                            time_quantum_dict['week'] = week_list
                            for a in agreement_list['fields']['d_time']:
                                data_jsons = TimeModel.objects.filter(t_id=a)
                                point_in_time_dict = {}
                                serialization_li = (json.loads(serializers.serialize('json', data_jsons)))
                                for b in serialization_li:
                                    # 时间点
                                    point_in_time_dict['time_id'] = b['pk']
                                    point_in_time_dict['t_name'] = b['fields']['t_name']
                                    point_in_time_dict['t_number'] = b['fields']['t_number']
                                    point_in_time_dict['t_start_time'] = b['fields']['t_start_time']
                                    li.append(b['fields']['t_start_time'][0:5])
                                    point_in_time_dict['t_end_time'] = b['fields']['t_end_time']
                                point_in_time.append(point_in_time_dict)
                            time_quantum_dict['datetime'] = point_in_time
                            time_quantum_list.append(time_quantum_dict)
                            # 判断时间和星期几是不是正确的
                            if len(ReservationOrderModel.objects.filter(project_id=project_id, r_data=time,
                                                                        r_time=timing)) == 0:
                                if verify_datetime(start, end, time) and is_verify(time, week_list):
                                    if timing in set(li):
                                        # 判断是否超过预约日期
                                        if is_timing(time) <= int(p['fields']['p_day']):
                                            order = getrand()
                                            ReservationOrderModel.objects.create(r_order_number=order,
                                                                                 reservation_number=1,
                                                                                 r_IDcard=ID_card,
                                                                                 project_id=project_id,
                                                                                 r_time=timing, r_data=time)
                                            data = {
                                                'msg': "预约成功 ",
                                                'code': 2000,
                                            }
                                            return Response(data)
                                        else:
                                            data = {
                                                'msg': "超出预约日期 ",
                                                'code': 4003,
                                            }
                                            return Response(data)
                                    else:
                                        data = {
                                            'msg': "该时间点不能预约 ",
                                            'code': 4002,
                                        }
                                        return Response(data)
                                else:
                                    data = {
                                        'msg': "不在预约时间范围内",
                                        'code': 4002,
                                    }
                                    return Response(data)
                            else:
                                number = json.loads(serializers.serialize('json', ReservationOrderModel.objects.filter(
                                    project_id=project_id, r_data=time, r_time=timing)))
                                if int(number[0]['fields']['reservation_number']) < int(p['fields']['p_number']):
                                    if verify_datetime(start, end, time) and is_verify(time, week_list):
                                        if timing in set(li):
                                            # 判断是否超过预约日期
                                            if is_timing(time) <= int(p['fields']['p_day']):
                                                order = getrand()
                                                ReservationOrderModel.objects.create(r_order_number=order,
                                                                                     reservation_number=1,
                                                                                     r_IDcard=ID_card,
                                                                                     project_id=project_id,
                                                                                       r_time=timing, r_data=time)
                                                data = {
                                                    'msg': "预约成功 ",
                                                    'code': 2000,
                                                }
                                                return Response(data)
                                            else:
                                                data = {
                                                    'msg': "超出预约日期 ",
                                                    'code': 4003001,
                                                }
                                                return Response(data)
                                        else:
                                            data = {
                                                'msg': "该时间点不能预约 ",
                                                'code': 400201,
                                            }
                                            return Response(data)
                                    else:
                                        data = {
                                            'msg': "不在预约时间范围内",
                                            'code': 400201,
                                        }
                                        return Response(data)
                                else:
                                    data = {
                                        'msg': "当前时间点预约满了",
                                        'code': 400201,
                                    }
                                    return Response(data)

                    else:
                        data = {
                            'msg': " 您不符合预约条件 ",
                            'code': 4002,
                        }
                        return Response(data)
                else:
                    date = json.loads(serializers.serialize('json', is_null))[0]['fields']['r_data'][0:4]
                    if date == datetime.datetime.now().strftime("%Y-%m-%d")[0:4]:
                        data = {
                            'msg': "今年不能再预约",
                            'code': 4002,
                        }
                        return Response(data)
                    else:
                        if is_check(start_time, end_time, age) and is_sex(p_sex, sex):
                            # 获取预约时间  判断预约时间是否在范围内
                            agreement_json = TimeQuantumModel.objects.filter(project__p_id=project_id).all()
                            agreement_lists = (json.loads(serializers.serialize('json', agreement_json)))
                            # print(type(ProjectModel.objects.filter(p_id=tj_id).first()))
                            p_json = ProjectModel.objects.filter(p_id=project_id)
                            p = (json.loads(serializers.serialize('json', p_json)))[0]
                            time_quantum_list = []
                            for agreement_list in agreement_lists:
                                start = agreement_list['fields']['start_time']
                                end = agreement_list['fields']['end_time']
                                ProjectModel.objects.filter()
                                time_quantum_dict = {}
                                point_in_time = []
                                time_quantum_dict['p_money'] = p['fields']['p_money']
                                time_quantum_dict['p_prepay'] = p['fields']['p_prepay']
                                time_quantum_dict['p_day'] = p['fields']['p_day']
                                time_quantum_dict['p_number'] = p['fields']['p_number']
                                time_quantum_dict['start_time'] = agreement_list['fields']['start_time']
                                time_quantum_dict['end_time'] = agreement_list['fields']['end_time']
                                data_jsons = DataTimeModel.objects.filter(time__t_id=agreement_list['pk']).all()
                                serialization_list = (json.loads(serializers.serialize('json', data_jsons)))
                                week_list = []
                                li = []
                                for i in serialization_list:
                                    week_list.append(i['fields']['d_data'])
                                time_quantum_dict['week'] = week_list
                                for a in agreement_list['fields']['d_time']:
                                    data_jsons = TimeModel.objects.filter(t_id=a)
                                    point_in_time_dict = {}
                                    serialization_li = (json.loads(serializers.serialize('json', data_jsons)))
                                    for b in serialization_li:
                                        # 时间点
                                        point_in_time_dict['time_id'] = b['pk']
                                        point_in_time_dict['t_name'] = b['fields']['t_name']
                                        point_in_time_dict['t_number'] = b['fields']['t_number']
                                        point_in_time_dict['t_start_time'] = b['fields']['t_start_time']
                                        li.append(b['fields']['t_start_time'][0:5])
                                        point_in_time_dict['t_end_time'] = b['fields']['t_end_time']
                                    point_in_time.append(point_in_time_dict)
                                time_quantum_dict['datetime'] = point_in_time
                                time_quantum_list.append(time_quantum_dict)
                                # 判断时间和星期几是不是正确的
                                if verify_datetime(start, end, time) and is_verify(time, week_list):
                                    if timing in set(li):
                                        # 判断是否超过预约日期
                                        if is_timing(time) <= int(p['fields']['p_day']):
                                            order = getrand()
                                            ReservationOrderModel.objects.create(r_order_number=order,
                                                                                 reservation_number=1,
                                                                                 r_IDcard=ID_card,
                                                                                 project_id=project_id,
                                                                                 r_time=timing, r_data=time)
                                            data = {
                                                'msg': "预约成功 ",
                                                'code': 20000,
                                            }
                                            return Response(data)
                                        else:
                                            data = {
                                                'msg': "超出预约日期 ",
                                                'code': 40030,
                                            }
                                            return Response(data)
                                    else:
                                        data = {
                                            'msg': "该时间点不能预约 ",
                                            'code': 40020,
                                        }
                                        return Response(data)
                                else:
                                    data = {
                                        'msg': "不在预约时间范围内",
                                        'code': 40020,
                                    }
                                    return Response(data)
                        else:
                            data = {
                                'msg': " 您不符合预约条件 ",
                                'code': 40020,
                            }
                            return Response(data)

        else:
            data = {
                'msg': "用户不存在",
                'code': 4000,
            }
            return Response(data)


# 99体检
class NineView(APIView):
    def post(self, request, *args, **kwargs):
        pass


# 母婴保健
class InfantAndMomView(APIView):
    def post(self, request, *args, **kwargs):
        Id_card = request.POST['id_card']
        project_id = request.POST['project_id']
        data = request.POST['data']
        time = request.POST['time']
        is_null = ReservationOrderModel.objects.filter(project_id=project_id, r_IDcard=Id_card)
        if len(is_null) == 0:
            """
            判断预约表中  用户是否预约过该项目
            """
            pass
        else:
            pass


# 老年保健
class GerocomiaView(APIView):
    def post(self, request, *args, **kwargs):
        pass


class IsQuery(APIView):
    def post(self, request, *args, **kwargs):
        project_id = request.POST['project_id']
        # r_time = request.POST['r_time']
        r_data = request.POST['r_data']
        is_all = ReservationOrderModel.objects.filter(project_id=project_id, r_data=r_data)
        is_json = json.loads(serializers.serialize('json', is_all))
        agreement_json = TimeQuantumModel.objects.filter(project__p_id=project_id).all()
        agreement_lists = (json.loads(serializers.serialize('json', agreement_json)))
        p_json = ProjectModel.objects.filter(p_id=project_id)
        print(p_json)
        p = (json.loads(serializers.serialize('json', p_json)))[0]
        time_quantum_list = []
        date = []

        for agreement_list in agreement_lists:
            ProjectModel.objects.filter()
            time_quantum_dict = {}
            point_in_time = []
            date_dict = {}
            time_quantum_dict['pk'] = project_id
            time_quantum_dict['p_name'] = p['fields']['p_name']
            time_quantum_dict['p_money'] = p['fields']['p_money']
            time_quantum_dict['p_prepay'] = p['fields']['p_prepay']
            time_quantum_dict['p_note'] = p['fields']['p_note']
            time_quantum_dict['p_day'] = p['fields']['p_day']
            time_quantum_dict['p_number'] = p['fields']['p_number']
            time_quantum_dict['t_name'] = agreement_list['fields']['t_name']
            time_quantum_dict['start_time'] = agreement_list['fields']['start_time']
            time_quantum_dict['end_time'] = agreement_list['fields']['end_time']
            date_dict['start_time'] = agreement_list['fields']['start_time']
            date_dict['end_time'] = agreement_list['fields']['end_time']
            # print(date_dict)
            data_jsons = DataTimeModel.objects.filter(time__t_id=agreement_list['pk']).all()
            serialization_list = (json.loads(serializers.serialize('json', data_jsons)))
            week_list = []
            for i in serialization_list:
                week_list.append(i['fields']['d_data'])
            time_quantum_dict['week'] = week_list
            for a in agreement_list['fields']['d_time']:
                data_jsons = TimeModel.objects.filter(t_id=a)
                point_in_time_dict = {}
                serialization_li = (json.loads(serializers.serialize('json', data_jsons)))
                for b in serialization_li:
                    # 时间点
                    point_in_time_dict['time_id'] = b['pk']
                    point_in_time_dict['t_name'] = b['fields']['t_name']
                    point_in_time_dict['t_number'] = b['fields']['t_number']
                    point_in_time_dict['t_start_time'] = b['fields']['t_start_time']
                    point_in_time_dict['t_end_time'] = b['fields']['t_end_time']
                point_in_time.append(point_in_time_dict)
            time_quantum_dict['datetime'] = point_in_time
            time_quantum_list.append(time_quantum_dict)
            date.append(date_dict)
        print(time_quantum_list[0]['p_day'])
        # 判断日期是否在时间范围内  星期几是否可以预约  是否超出预约期限
        if verify_datetime(time_quantum_list[0]['start_time'], time_quantum_list[0]['end_time'], r_data) and is_verify(
                r_data, time_quantum_list[0]['week']) and is_timing(r_data) < int(time_quantum_list[0]['p_day']):
            data = {
                'msg': "符合实际范围",
                'code': 2000,
                # 'data': time_quantum_list
            }
            return Response(data)
        else:
            data = {
                'msg': "不符合实际范围",
                'code': 4000,
            }
            return Response(data)
        # for a in date:
        #     if verify_datetime(a['start_time'], a['end_time'], r_data):
        #         # fff = is_verify(r_data,)
        #         # print(fff,"aaa")
        #         data = {
        #             'msg': "符合实际范围",
        #             'code': 2000,
        #         }
        #         return Response(data)

        # for a in date:
        #     while verify_datetime(a['start_time'], a['end_time'], r_data):
        #         print("存在")
        #
        #         break
        #     else:
        #         print("11")
        #         break

        # data = {
        #     'msg': "查询成功",
        #     'code': 2000,
        #     'data': time_quantum_list
        # }
        # return Response(data)
